//
//  RPCService.swift
//  Center_RPC
//
//  Created by Flutter on 2021/7/12.
//

import Foundation
import Standard
import GRPC
import NIO
import NIOSSL


open class RPCService {
    private let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)

    private let name: String

    private(set) var connection: ClientConnection

    private(set) lazy var logger = Loggers["\(typeName).\(name)"]

    public init(name: String, host: String, port: Int, cert: String, trustHost: String) {
        precondition(!name.isEmpty, "name should not be empty")
        self.name = name
        let certificate = try! NIOSSLCertificate(bytes: .init(cert.utf8), format: .pem)
        let builder  =  ClientConnection.secure(group: group)
            .withTLS(trustRoots: .certificates([certificate]))
            .withTLS(serverHostnameOverride: trustHost)
        connection = builder.connect(host: host, port: port)
    }

    deinit {
        try? group.syncShutdownGracefully()
    }
}

extension RPCService {
    func change(host: String, port: Int, cert: String, trustHost: String) {
        do {
            try connection.close().wait()
        } catch {
            logger.error("\(error)")
        }
        let certificate = try! NIOSSLCertificate(bytes: .init(cert.utf8), format: .pem)
        let builder  =  ClientConnection.secure(group: group)
            .withTLS(trustRoots: .certificates([certificate]))
            .withTLS(serverHostnameOverride: trustHost)
        connection = builder.connect(host: host, port: port)
    }
}

extension RPCService: TypeName {}

